<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{name}}管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" maxlength="50" show-word-limit v-model="formInline.q" placeholder="输入关键字"></el-input>
      </el-form-item>
      <el-select v-model.number="formInline.belong_grade" clearable placeholder="选择等级">
        <el-option v-for="item in gradeList" :key="item.choice" type="number" :label="item.description" :value="item.choice"></el-option>
      </el-select>
      <el-select v-model="formInline.type" clearable placeholder="选择类型">
        <el-option v-for="item in typeList" :key="item.choice" :label="item.description" :value="item.choice"></el-option>
      </el-select>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd()">添加</el-button>
      </el-form-item>
    </el-form>
    <el-button size="small" type="warning" icon="el-icon-search" @click="searchUseless">查看禁用</el-button>
    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column prop="title" label="问题" width="250">
      </el-table-column>
      <el-table-column align="center" sortable prop="type" label="类型" width="100">
      </el-table-column>
      <el-table-column align="center" sortable prop="belong_grade" label="所属等级" width="100">
      </el-table-column>
      <el-table-column align="center" sortable prop="useful" label="状态" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.useful"
            :active-value="useful.active"
            :inactive-value="useful.inactive"
            @change="handle(scope.row.useful, scope.$index)"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">查看</el-button>
          <!-- <el-button size="mini" type="primary" @click="handleOpen(scope.$index)">开放</el-button>
          <el-button size="mini" type="danger" @click="handleClose(scope.$index)">禁用</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
      background
      layout="prev, pager, next, total"
      :current-page="pageparm.currentPage"
      :page-size="pageparm.pageSize"
      :total="pageparm.total"
      @current-change="changePage"
      @prev-click="changePage"
      @next-click="changePage">
    </el-pagination>
    <!-- 添加界面 -->
    <el-dialog :close-on-click-modal="false" :title="`${title}${name}`" :visible.sync="addFormVisible" width="70%" @click="closeDialog">
      <el-form label-width="120px" :model="addForm" :rules="rules" ref="addForm">
        <el-form-item label="考题名称" prop="title">
          <el-input size="small" maxlength="50" show-word-limit v-model="addForm.title" auto-complete="off" placeholder="必填（少于50个字符）"></el-input>
        </el-form-item>
        <el-form-item label="考题类型" prop="type">
          <el-select v-model="addForm.type" placeholder="必选" @change="changeType">
            <el-option v-for="item in typeList" :key="item.choice" :label="item.description" :value="item.choice"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属等级" prop="belong_grade">
          <el-select v-model="addForm.belong_grade" placeholder="必选">
            <el-option v-for="item in gradeList" :key="item.choice" :label="item.description" :value="item.choice"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="addForm.type === 'choice'" label="图片" prop="img_list">
          <el-upload
            class="upload-demo"
            :action="uploadImageUrl"
            name="file_obj"
            :headers="uploadHeaders"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :on-error="handleError"
            :before-upload="handleBeforeUpload"
            :file-list="fileList"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2mb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="" prop="img_list">
          <p class="img-url" v-for="item in fileList" :key="item.uid">{{$store.state.imgUrlPix + item.response.data}}</p>
        </el-form-item>
        <el-form-item
          v-show="addForm.type === 'choice'"
          v-for="(item, index) in addForm.optionsL"
          :label="`选项${index + 1}`"
          :key="item.key"
          :prop="`optionsL[${index}].value`"
          :rules="{required: true, message: '该选项不能为空', trigger: 'blur'}">
          <el-input v-model="item.value"></el-input>
          <el-button @click.prevent="removeOption(index)">删除</el-button>
        </el-form-item>
        <el-form-item v-if="addForm.type === 'choice'" label="答案选项" prop="answer">
          <el-checkbox-group v-model="addForm.answer">
            <el-checkbox v-for="(item, index) in addForm.optionsL" :key="item.key" :label="index" type="number">选项{{index+1}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <div class="chess" v-if="reset" v-show="typeChess.includes(addForm.type)">
          <div class="chess-board">
            <div v-for="(item, index) in Array(90)"
              :id="`place${index}`"
              :key="item"
              class="item"
              @dragover="allowDrop"
              @drop="drop"
              :class="{'pending-place': move.pending}"
              @click.stop="toSel(`place${index}`)">
              <img
                v-if="copychessObj.hasOwnProperty(`${'place' + index}`)"
                :id="`${copychessObj['place' + index]}`"
                :src="`./static/assets/img/chess_pieces/${copychessObj['place' + index].replace(/\d/g, '')}.png`"
                class="item"
                :draggable="true"
                @dragstart="dragstart"
                :class="{'pending': move.nowId === copychessObj['place' + index]}"
                @click.stop="toSel(copychessObj['place' + index])">
            </div>
          </div>
          <div class="chess-piece" id="chessPiece">
            <template v-for="item in piece_name_list">
              <img
                v-if="!copychessObj.hasOwnProperty(item)"
                :id="`${item}`"
                :key="item"
                :src="`./static/assets/img/chess_pieces/${item.replace(/\d/g, '')}.png`"
                class="item"
                :draggable="true"
                @dragstart="dragstart"
                :class="{'pending': move.nowId === item}"
                @click.stop="toSel(item)">
            </template>
          </div>
        </div>
        <div v-show="typeChess.includes(addForm.type)">
          <p class="chess-p">{{chess.title}}阶段</p>
          <p class="tip">默认状态为布局阶段，拖动棋盘外棋子到棋盘内，设置布局</p>
          <p class="tip">设置完布局之后，点击开始走棋，即变为走棋阶段，即设置答案</p>
          <p class="tip">若为一步杀，需操作一次；若为两步杀，需要操作三次，答案顺序为玩家->电脑->玩家</p>
        </div>
        <el-form-item v-if="typeChess.includes(addForm.type)" label="答案操作" prop="answer">
          <el-input v-for="item in chess.answer" :key="item.label" v-model="item.label" :disabled="true"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitAddForm('addForm')">提交</el-button>
        <el-button v-show="addForm.type === 'choice'" size="small" type="success" class="title" @click="addOption()">添加选项</el-button>
        <el-button v-show="typeChess.includes(addForm.type)" size="small" type="success" class="title" @click="toOperate()">开始走棋</el-button>
        <el-button v-show="typeChess.includes(addForm.type)" size="small" type="success" class="title" @click="reOperate()">重新走棋</el-button>
        <el-button v-show="typeChess.includes(addForm.type)" size="small" type="danger" class="title" @click="resetChess()">清空棋盘</el-button>
      </div>
    </el-dialog>

    <!-- 编辑页面 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="editFormVisible" width="70%" @click="closeDialog">
      <el-form v-if="editForm.type === 'choice'" label-width="120px" :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="考题名称" prop="title">
          <el-input :disabled="true" size="small" maxlength="50" show-word-limit v-model="editForm.title" auto-complete="off" placeholder="必填（少于50个字符）"></el-input>
        </el-form-item>
        <el-form-item label="考题类型" prop="type">
           <el-input :disabled="true" size="small" v-model="editForm.type"></el-input>
        </el-form-item>
        <el-form-item label="所属等级" prop="belong_grade">
          <el-select disabled v-model="editForm.belong_grade" placeholder="必选">
            <el-option v-for="item in gradeList" :key="item.choice" :label="item.description" :value="item.choice"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="editForm.type === 'choice'" label="图片" prop="img_list">
          <el-upload
            class="upload-demo"
            :action="uploadImageUrl"
            name="file_obj"
            :headers="uploadHeaders"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :on-error="handleError"
            :before-upload="handleBeforeUpload"
            :file-list="fileListEdit"
            list-type="picture">
            <el-button disabled size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="" prop="img_list">
          <p class="img-url" v-for="item in fileListEdit" :key="item.uid">{{$store.state.imgUrlPix + item.response.data}}</p>
        </el-form-item>
        <el-form-item
          v-show="editForm.type === 'choice'"
          v-for="(item, index) in editForm.optionsL"
          :label="`选项${index + 1}`"
          :key="item.key"
          :prop="`optionsL[${index}].value`"
          :rules="{required: true, message: '该选项不能为空', trigger: 'blur'}">
          <el-input v-model="item.value" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item v-if="editForm.type === 'choice'" label="答案选项" prop="answer">
          <el-checkbox-group disabled v-model="editForm.answer">
            <el-checkbox v-for="(item, index) in editForm.optionsL" :key="item.key" :label="index" type="number">选项{{index+1}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <el-form v-else label-width="120px" :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="考题名称" prop="title">
          <el-input :disabled="true" size="small" maxlength="50" show-word-limit v-model="editForm.title" auto-complete="off" placeholder="必填（少于50个字符）"></el-input>
        </el-form-item>
        <el-form-item label="考题类型" prop="type">
           <el-input :disabled="true" size="small" v-model="editForm.type"></el-input>
        </el-form-item>
        <el-form-item label="所属等级" prop="belong_grade">
          <el-select disabled v-model="editForm.belong_grade" placeholder="必选">
            <el-option v-for="item in gradeList" :key="item.choice" :label="item.description" :value="item.choice"></el-option>
          </el-select>
        </el-form-item>
        <div class="chess" v-show="typeChess.includes(editForm.type)">
          <div class="chess-board">
            <div v-for="(item, index) in Array(90)"
              :id="`place${index}`"
              :key="item"
              class="item">
              <img
                v-if="copychessObj.hasOwnProperty(`place${index}`)"
                :id="`${copychessObj[`place${index}`]}`"
                :src="`./static/assets/img/chess_pieces/${copychessObj[`place${index}`].replace(/\d/g, '')}.png`"
                class="item">
            </div>
          </div>
          <div class="chess-piece" id="chessPiece">
            <template v-for="item in piece_name_list">
              <img
                v-if="!copychessObj.hasOwnProperty(item)"
                :id="`${item}`"
                :key="item"
                :src="`./static/assets/img/chess_pieces/${item.replace(/\d/g, '')}.png`"
                class="item">
            </template>
          </div>
        </div>
        <div v-show="typeChess.includes(editForm.type)">
          <p class="tip">若为一步杀，需操作一次；若为两步杀，需要操作三次，答案顺序为玩家->电脑->玩家</p>
        </div>
        <el-form-item v-if="typeChess.includes(editForm.type)" label="答案操作" prop="answer">
          <el-input v-for="item in chess.answer" :key="item.label" v-model="item.label" :disabled="true"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { questionList, questionListSearch, questionGradeList, questionTypeList,
  activityDetail, uploadImage, questionListUseless,
  questionAdd, questionUpdate, questionOpen, questionClose, uploadImageUrl } from '../../api/userMG'
export default {
  data() {
    return {
      //
      move: {
        pending: false,
        preId: '',
        nowId: '',
      },
      //
      loading: false, //是显示加载
      addFormVisible: false, //控制页面显示
      editFormVisible: false, //控制页面显示
      title: '添加',
      name: '题库',
      fileList: [],fileListEdit: [],
      gradeList: [],
      typeList: [],
      reset: false,
      useful: {
        active: 1,
        inactive: 0
      },
      typeChess: ['one_step_play', 'two_step_play'],
      chess: {
        title: '设置布局',
        layout: true,
        operate: false,
        answer: [],
      },
      chessObj: {},
      copychessObj: {},
      addForm: {
        title: '',
        type: '',
        belong_grade: '',
        img_list: [],
        operation_question: {
          chessboard: [],
          move_record: []
        },
        optionsL:[],
        choice_list: [],
        answer: [],
        token: localStorage.getItem('logintoken')
      },
      editForm: {
        main_id: -1,
        title: '',
        type: '',
        belong_grade: '',
        img_list: [],
        operation_question: {
          chessboard: [],
          move_record: []
        },
        optionsL:[],
        choice_list: [],
        answer: [],
        token: localStorage.getItem('logintoken')
      },
      uploadHeaders: {
        token: localStorage.getItem('logintoken')
      },
      // rules表单验证
      rules: {
        title: [
          { required: true, message: '请输入考题名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度小于50个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        belong_grade: [
          { required: true, message: '请选择等级', trigger: 'change' }
        ],
        answer: [
          { type: 'array', required: true, message: '答案不能为空', trigger: 'change' }
        ],
      },
      formInline: {
        searchUselessBoolean: false,
        location_id: 999999,
        page_index: 1,
        page_size: 15,
        q: '',
        belong_grade: '',
        type: '',
        token: localStorage.getItem('logintoken')
      },
      listData: [], //用户数据
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 15,
        total: 0
      },

      piece_name_list: [
        "down_bing1",
        "down_bing2",
        "down_bing3",
        "down_bing4",
        "down_bing5",
        "down_che1",
        "down_che2",
        "down_ma1",
        "down_ma2",
        "down_pao1",
        "down_pao2",
        "down_shi1",
        "down_shi2",
        "down_xiang1",
        "down_xiang2",
        "down_shuai",
        "up_cu1",
        "up_cu2",
        "up_cu3",
        "up_cu4",
        "up_cu5",
        "up_jv1",
        "up_jv2",
        "up_ma1",
        "up_ma2",
        "up_pao1",
        "up_pao2",
        "up_shi1",
        "up_shi2",
        "up_xiang1",
        "up_xiang2",
        "up_jiang",
      ]
    }
  },
  // 注册组件
  components: {},
  /**
   * 创建完毕
   */
  created() {
    this.getTypelist()
    this.getGradelist()
    this.getdata(this.formInline)
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    changePage(cur){
      this.pageparm.currentPage = cur;
      this.formInline.page_index = cur;
      this.getdata(this.formInline);
    },
    // 获取列表
    getdata(parameter) {
      this.loading = true
      let target = {}
      Object.assign(target ,parameter);
      if (!target.belong_grade) delete target.belong_grade
      if (!target.type) delete target.type
      let rep
      if (this.formInline.searchUselessBoolean) {
        rep = questionListUseless(target)
      } else {
        rep = !target.belong_grade && !target.type ? questionListSearch(target) : questionList(target)
      }
      rep.then(res => {
          this.loading = false
          if (res.code === 0) {
            this.listData = res.data.list
            this.pageparm.currentPage = this.formInline.page_index
            this.pageparm.pageSize = this.formInline.page_size
            this.pageparm.total = res.data.total_items
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('加载失败，请稍后再试！')
        })
    },
    getTypelist() {
      let rep = questionTypeList()
      rep.then(res => {
        if (res.code === 0) {
          this.typeList = res.data
        } else {
          this.$message({
            type: 'info',
            message: res.msg
          })
        }
      })
      .catch(err => {
        this.loading = false
        this.$message.error('加载失败，请稍后再试！')
      })
    },
    getGradelist() {
      let rep = questionGradeList()
      rep.then(res => {
        if (res.code === 0) {
          this.gradeList = res.data
        } else {
          this.$message({
            type: 'info',
            message: res.msg
          })
        }
      })
      .catch(err => {
        this.loading = false
        this.$message.error('加载失败，请稍后再试！')
      })
    },
    handleBeforeUpload(file) {
      const isImage = file.type.includes("image");
      if (!isImage) {
        this.$message.error("上传文件类型必须是图片!");
      }
      return isImage;
    },
    // name uid
    handleSuccess(res, file, fL) {
      // console.log('success', res, file, fL);
      if (res.code === 0) {
        if (this.title === '添加') {
          this.fileList = fL
        } else {
          this.fileListEdit = fL
        }
      } else {
        this.$message.error(res.msg)
      }
    },
    handleRemove(file, fL) {
      // console.log(file, fL, this.fileList);
      if (this.title === '添加') {
        this.fileList = fL
      } else {
        this.fileListEdit = fL
      }
    },
    handleError(err, file, fileList) {
      this.$message.error('加载失败，请稍后再试！')
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.page_index = parm.currentPage
      this.formInline.page_size = parm.pageSize
      this.getdata(this.formInline)
    },
    // 搜索事件
    search() {
      this.formInline.searchUselessBoolean = false
      this.getdata(this.formInline)
    },
    //
    searchUseless() {
      this.formInline.searchUselessBoolean = true
      this.getdata(this.formInline)
    },
    //显示添加界面
    handleAdd() {
      this.addFormVisible = true
      this.title = '添加'
      this.copychessObj = {}
      this.chessObj = {}
      this.chess =  {
        title: '设置布局',
        layout: true,
        operate: false,
        answer: [],
      }
    },
    removeOption(index) {
      this.addForm.optionsL.splice(index, 1)
    },
    addOption() {
      this.addForm.optionsL.push({
        value: '',
        key: Date.now()
      });
    },
    handleEdit: function(index, row) {
      let that = this
      this.title = '修改'
      setTimeout(function(){
        that.editForm.main_id = row.main_id
        that.editForm.type = row.type
        that.editForm.belong_grade = row.belong_grade
        that.editForm.title = row.title
        that.editForm.answer = row.answer
        that.editForm.img_list = row.img_list
        that.fileListEdit = []
        for(let i = 0; i < that.editForm.img_list.length; i++){
          that.fileListEdit.push({
            name: '',
            url: `${that.$store.state.imgUrlPix}${that.editForm.img_list[i]}`,
            response: {data: that.editForm.img_list[i]}
          })
        }
        if (row.type === 'choice') {
          that.editForm.choice_list = row.choice_list
          that.editForm.optionsL = []
          for(let i = 0; i < that.editForm.choice_list.length; i++){
            that.editForm.optionsL.push({
              value: that.editForm.choice_list[i],
              key: i
            })
          }
        }
        // 设置走棋阶段
        // operation_question chessboard [[x,y,name]] move_record [{from:[],to:[]},{},{}]
        // chessObj { palce33: name } copychessObj
        // chess: {
        //   title: '设置布局',
        //   layout: true,
        //   operate: false,
        //   answer: [],
        // },
        if (that.typeChess.includes(row.type)) {
          that.chessObj = {}
          for (let i = 0; i < row.operation_question.chessboard.length; i++) {
            let place = row.operation_question.chessboard[i]
            if (place.length >= 3) {
              that.chessObj[`place${place[0] * 9 + place[1]}`] = place[2]
              that.chessObj[place[2]] = `place${place[0] * 9 + place[1]}`
              that.copychessObj = Object.assign(that.chessObj, {})
            }
          }
          that.chess.answer = []
          for (let i = 0; i < row.operation_question.move_record.length; i++) {
            let move = row.operation_question.move_record[i]
            if (move && move.from) {
              let from = `[${move.from[0]},${move.from[1]}]`
              let to = `[${move.to[0]},${move.to[1]}]`
              that.chess.answer.push({
                label: `from ${from} to ${to}`,
                value: move
              })
            }
          }
        }
        that.loading = false
        that.editFormVisible = true
      }, 0)
    },
    // 编辑、增加页面保存方法
    submitAddForm(addData) {
      if (this.addForm.type === 'choice') {
        for (let i = 0; i < this.fileList.length; i++) {
          this.addForm.img_list.push(this.fileList[i].response.data)
        }
        this.addForm.choice_list = []
        for (let i = 0; i < this.addForm.optionsL.length; i++) {
          this.addForm.choice_list.push(this.addForm.optionsL[i].value)
        }
      }
      if (this.addForm.type === 'one_step_play') {
        this.addForm.answer = []
        if (this.chess.answer.length !== 1) {
          this.$message.error('一步杀，答案仅且共需要一步！')
          return
        }
        for (let i = 0; i < this.chess.answer.length; i++) {
          this.addForm.answer.push(this.chess.answer[i].value)
          this.addForm['operation_question'].move_record.push(this.chess.answer[i].value)
        }
      }
      if (this.addForm.type === 'two_step_play') {
        this.addForm.answer = []
        if (this.chess.answer.length !== 3) {
          this.$message.error('两步杀，答案仅且共需要三步！')
          return
        }
        for (let i = 0; i < this.chess.answer.length; i++) {
          if (i !== 1) { // 只录入玩家
            this.addForm.answer.push(this.chess.answer[i].value)
          }
          this.addForm['operation_question'].move_record.push(this.chess.answer[i].value)
        }
      }
      if (this.typeChess.includes(this.addForm.type)) {
        // up_che1 place33  位置 + 棋种
        for (let key in this.chessObj) {
          if (key.includes('place')) {
            this.addForm['operation_question'].chessboard.push([Math.floor(key.split('place')[1]/9), key.split('place')[1] % 9, this.chessObj[key]])
          }
        }
      }
      //  ??? answer
      this.$refs[addData].validate(valid => {
        if (valid) {
          if (this.typeChess.includes(this.addForm.type)) delete this.addForm.img_list
          if (this.typeChess.includes(this.addForm.type)) delete this.addForm.choice_list
          if (this.addForm.type === 'choice') delete this.addForm.operation_question
          questionAdd(this.addForm).then(res => {
              this.addFormVisible = false
              this.loading = false
              if (res.code === 0) {
                // 重设添加
                this.fileList = []
                this.emptyChess()
                this.addForm = {
                  title: '',
                  type: '',
                  belong_grade: 1,
                  img_list: [],
                  operation_question: {},
                  optionsL:[],
                  choice_list: [],
                  answer: [],
                  token: localStorage.getItem('logintoken')
                }
                this.getdata(this.formInline)
                this.$message({
                  type: 'success',
                  message: '提交成功！'
                })
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.addFormVisible = false
              this.loading = false
              this.$message.error('提交失败，请稍后再试！')
            })
        } else {
          this.addForm.img_list = []
          return false
        }
      })
    },
    submitEditForm(editData) {
      let buff = this.editForm.img_list
      this.editForm.img_list = []
      for (let i = 0; i < this.fileListEdit.length; i++) {
        this.editForm.img_list.push(this.fileListEdit[i].response.data)
      }
      this.$refs[editData].validate(valid => {
        if (valid) {
          activityUpdate(this.editForm)
            .then(res => {
              this.editFormVisible = false
              this.loading = false
              if (res.code === 0) {
                this.getdata(this.formInline)
                this.$message({
                  type: 'success',
                  message: '提交成功！'
                })
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.addFormVisible = false
              this.loading = false
              this.$message.error('提交失败，请稍后再试！')
            })
        } else {
          this.editForm.img_list = buff
          return false
        }
      })
    },
    handle(cur, index) {
      if (cur) {
        this.postUseful(true, index)
      } else {
        this.postUseful(false, index)
      }
    },
    handleOpen(index) {
      this.$confirm('确定要开放考题吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        this.postUseful(true, index)
      })
      .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    handleClose(index) {
      this.$confirm('确定要关闭考题吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.postUseful(false, index)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    postUseful(isOpen, index) {
      let rep = isOpen ? questionOpen({main_id: this.listData[index].main_id}) : questionClose({main_id: this.listData[index].main_id})
      let tip = isOpen ? '开放' : '关闭'
      rep.then(res => {
        if (res.code === 0) {
          this.$message({
            type: 'success',
            message: `考题已${tip}!`
          })
          this.getdata(this.formInline)
        } else {
          this.$message({
            type: 'info',
            message: res.msg
          })
        }
      })
      .catch(err => {
        this.loading = false
        this.$message.error('请求失败，请稍后再试！')
      })
    },
    toUrl(index, row) {
      this.$router.push(`/certificate/applicationList?main_id=${row.main_id}`)
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.addFormVisible = false;
      this.editFormVisible = false
    },
    changeType(e) {
      this.addForm.answer = []
      if(this.typeChess.includes(e)) {
        this.reset = true
      }
    },
    toOperate() {
      this.chess.layout = false
      this.chess.operate = true
      this.chess.title = '设置走棋'
    },
    reOperate() { // 重新走棋
      this.reset = false
      let that = this
      that.move.pending = false
      that.chess.answer.length = 0
      that.chess.layout = false
      that.chess.operate = true
      that.chess.title = '设置走棋'
      that.copychessObj = Object.assign(that.chessObj, {})
      setTimeout(function(){
        that.reset = true
      }, 0)
    },
    resetChess() { // 清空棋盘
      this.reset = false
      let that = this
      setTimeout(this.emptyChess, 0)
    },
    emptyChess() {
      this.move.pending = false
      this.chessObj = {}
      this.copychessObj = {}
      this.chess.answer.length = 0
      this.chess.layout = true
      this.chess.operate = false
      this.chess.title = '设置布局'
      this.reset = true
    },
    dragstart(ev)
    {
      ev.dataTransfer.setData("piece", ev.target.id);
    },
    allowDrop(ev)
    {
      ev.preventDefault();
    },
    drop(ev)
    {
      ev.preventDefault();
      let data = ev.dataTransfer.getData("piece");
      if (this.chess.layout) {
        if (data !== ev.path[0].id) { // 非原地移动
          if (this.chessObj.hasOwnProperty(data)) { // 是在棋盘内的棋子
            delete this.chessObj[this.chessObj[data]]
            delete this.chessObj[data]
          }
          if (ev.target.id.includes('place')) { // 非抢位移动
            ev.target.appendChild(document.getElementById(data))
            this.chessObj[data] = ev.srcElement.id
            this.chessObj[ev.srcElement.id] = data // 易初始化布局
          } else { // 抢位移动
            // place <----> id
            let emP = ev.target.parentElement
            let em = ev.target.parentElement.childNodes[0].id ? ev.target.parentElement.childNodes[0] : ev.target.parentElement.childNodes[0 + 1] // 0可能为注释
            emP.removeChild(em)
            emP.appendChild(document.getElementById(data))
            document.getElementById('chessPiece').appendChild(em) // 布局栏目
            delete this.chessObj[this.chessObj[em.id]]
            delete this.chessObj[em.id]
            this.chessObj[data] = emP.id
            this.chessObj[emP.id] = data // 易初始化布局
          }
        }
      }
      if (this.chess.operate) {
        if (!this.chessObj.hasOwnProperty(data)) {
          this.$message.error('设置操作答案只能操作棋盘内棋子！')
          return
        }
        if (this.addForm.type === 'one_step_play' && this.chess.answer.length === 1) {
          this.$message.error('只能操作一步！')
          return
        }
        if (this.addForm.type === 'two_step_play' && this.chess.answer.length === 3) {
          this.$message.error('只能操作三步！')
          return
        }
        if (data !== ev.path[0].id) { // 非原地移动
          let fromE = document.getElementById(data).parentElement
          let from = `from [${Math.floor(fromE.id.split('place')[1]/9)},${fromE.id.split('place')[1] % 9}]`
          if (ev.target.id.includes('place')) {
            ev.target.appendChild(document.getElementById(data))
            let to = `to [${Math.floor(ev.target.id.split('place')[1]/9)},${ev.target.id.split('place')[1] % 9}]`
            this.chess.answer.push({
              label: `${from} ${to}`,
              value: {
                from: [Math.floor(fromE.id.split('place')[1]/9), fromE.id.split('place')[1] % 9],
                to: [Math.floor(ev.target.id.split('place')[1]/9), ev.target.id.split('place')[1] % 9]
              }
            })
          } else { // 吃子
            let emP = ev.target.parentElement
            let em = ev.target.parentElement.childNodes[0].id ? ev.target.parentElement.childNodes[0] : ev.target.parentElement.childNodes[0 + 1] // 0可能为注释
            emP.removeChild(em)
            emP.appendChild(document.getElementById(data))
            document.getElementById('chessPiece').appendChild(em) // 布局栏目
            let to = `to [${Math.floor(emP.id.split('place')[1]/9)},${emP.id.split('place')[1] % 9}]`
            this.chess.answer.push({
              label: `${from} ${to}`,
              value: {
                from: [Math.floor(fromE.id.split('place')[1]/9), fromE.id.split('place')[1] % 9],
                to: [Math.floor(emP.id.split('place')[1]/9), emP.id.split('place')[1] % 9]
              }
            })
          }
        }
      }
      // console.log(this.chessObj, this.copychessObj)
    },

    toSel(id) {
      if (this.chess.layout) {
        if (this.move.pending) {
          if (this.move.nowId === id) {
            this.move.pending = false
            this.move.preId = this.move.nowId
            this.move.nowId = ''
          } else {
            let nowId = this.move.nowId
            if (id.includes('place')) {
              // 场内移位，场外移位
              if (this.chessObj.hasOwnProperty(nowId)) {
                delete this.chessObj[this.chessObj[nowId]]
                delete this.chessObj[nowId]

                let nowEle = document.getElementById(nowId)
                let parEle = nowEle.parentElement
                let parNewEle = document.getElementById(id)

                parEle.removeChild(nowEle)
                parNewEle.appendChild(nowEle)
                this.chessObj[nowId] = parNewEle.id
                this.chessObj[parNewEle.id] = nowId
              } else {
                let nowEle = document.getElementById(nowId)
                let parEle = document.getElementById('chessPiece')
                let parNewEle = document.getElementById(id)

                parEle.removeChild(nowEle)
                parNewEle.appendChild(nowEle)
                this.chessObj[nowId] = parNewEle.id
                this.chessObj[parNewEle.id] = nowId
              }
            } else { // id 代表棋子
              // 排除场内抢场外，排除场外换场外
              // 场内抢场内位，场外抢场内位
              if (this.chessObj.hasOwnProperty(nowId)) {
                if (!this.chessObj.hasOwnProperty(id)) {
                  this.$message.error('场内棋子不能抢场外棋子布局，如若交换，请先点击场外棋子，再点击场内棋子！')
                  return
                }
                delete this.chessObj[this.chessObj[nowId]]
                delete this.chessObj[nowId]

                let nowEle = document.getElementById(nowId)
                let parEle = nowEle.parentElement
                let toEle = document.getElementById(id)
                let parNewEle = toEle.parentElement
                let chess = document.getElementById('chessPiece')

                parEle.removeChild(nowEle)
                parNewEle.removeChild(toEle)
                parNewEle.appendChild(nowEle)
                chess.appendChild(toEle)
                delete this.chessObj[this.chessObj[id]]
                delete this.chessObj[id]
                this.chessObj[nowId] = parNewEle.id
                this.chessObj[parNewEle.id] = nowId
              } else {
                if (!this.chessObj.hasOwnProperty(id)) {
                  this.move.pending = true
                  this.move.preId = nowId
                  this.move.nowId = id
                  return
                }
                let nowEle = document.getElementById(nowId)
                let parEle = nowEle.parentElement
                let toEle = document.getElementById(id)
                let parNewEle = toEle.parentElement
                let chess = document.getElementById('chessPiece')

                parEle.removeChild(nowEle)
                parNewEle.removeChild(toEle)
                parNewEle.appendChild(nowEle)
                chess.appendChild(toEle)
                delete this.chessObj[this.chessObj[id]]
                delete this.chessObj[id]
                this.chessObj[nowId] = parNewEle.id
                this.chessObj[parNewEle.id] = nowId
              }
            }
            this.move.pending = false
            this.move.preId = nowId
            this.move.nowId = ''
          }
        } else {
          if (!id.includes('place')) {
            this.move.pending = true
            this.move.nowId = id
          }
        }
      }

      if (this.chess.operate) {
        if (!this.move.pending) {
          if (!id.includes('place')) {
            if (!this.chessObj.hasOwnProperty(id)) {
              this.$message.error('设置操作答案只能操作棋盘内棋子！')
              return
            }
            if (this.addForm.type === 'one_step_play' && this.chess.answer.length === 1) {
              this.$message.error('只能操作一步！')
              return
            }
            if (this.addForm.type === 'two_step_play' && this.chess.answer.length === 3) {
              this.$message.error('只能操作三步！')
              return
            }
            this.move.pending = true
            this.move.nowId = id
          }
        } else { // 分抢位 和 移位
          // 排除点击场外棋子
          let nowId = this.move.nowId
          if (nowId !== id) {
            if (!id.includes('place')) {
              if (!this.chessObj.hasOwnProperty(id)) {
                this.$message.error('不能吃掉场外棋子！')
                return
              }
              let nowEle = document.getElementById(nowId)
              let parEle = nowEle.parentElement
              let toEle = document.getElementById(id)
              let parNewEle = toEle.parentElement
              let chess = document.getElementById('chessPiece')

              parEle.removeChild(nowEle)
              parNewEle.removeChild(toEle)
              parNewEle.appendChild(nowEle)
              chess.appendChild(toEle)
              let from = `from [${Math.floor(parEle.id.split('place')[1]/9)},${parEle.id.split('place')[1] % 9}]`
              let to = `to [${Math.floor(parNewEle.id.split('place')[1]/9)},${parNewEle.id.split('place')[1] % 9}]`
              this.chess.answer.push({
                label: `${from} ${to}`,
                value: {
                  from: [Math.floor(parEle.id.split('place')[1]/9), parEle.id.split('place')[1] % 9],
                  to: [Math.floor(parNewEle.id.split('place')[1]/9), parNewEle.id.split('place')[1] % 9]
                }
              })
            } else {
              let nowEle = document.getElementById(nowId)
              let parEle = nowEle.parentElement
              let parNewEle = document.getElementById(id)
              parEle.removeChild(nowEle)
              parNewEle.appendChild(nowEle)
              let from = `from [${Math.floor(parEle.id.split('place')[1]/9)},${parEle.id.split('place')[1] % 9}]`
              let to = `to [${Math.floor(parNewEle.id.split('place')[1]/9)},${parNewEle.id.split('place')[1] % 9}]`
              this.chess.answer.push({
                label: `${from} ${to}`,
                value: {
                  from: [Math.floor(parEle.id.split('place')[1]/9), parEle.id.split('place')[1] % 9],
                  to: [Math.floor(parNewEle.id.split('place')[1]/9), parNewEle.id.split('place')[1] % 9]
                }
              })
            }
          }
          this.move.pending = false
          this.move.preId = nowId
          this.move.nowId = ''
        }
      }
    },
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
.el-table--border, .el-table--group {
  margin: 20px 0;
}
.chess-board {
  background-image: url('../../assets/img/chessboard_v3.jpg');
  display: flex;
  flex-wrap: wrap;
  height: 480px;
  width: 432px;
  margin: 0 auto;
  background-repeat: round;
  justify-content: space-between;
}
.chess-board .item {
  width: 44px;
  border: 1px dashed #9e9e9e33;
  height: 40px;
  border-radius: 20px;
  overflow: hidden;
}
.chess-p {
  text-align: center;
  font-weight: bold;
  font-size: 22px;
  color: #d263e5;
}
.tip {
  text-align: center;
  font-weight: bold;
  font-size: 12px;
}
.chess-piece {
  display: flex;
  flex-wrap: wrap;
  height: 192px;
  width: 432px;
  margin: 0 auto;
  background-repeat: round;
  justify-content: space-between;
}
.chess-piece img {
  margin: 0 5px;
  width: 44px;
  height: 40px;
}
.img-url {
  border: 1px solid #333;
  border-radius: 10px;
  padding: 0 10px;
}
.pending {
  transform: translate(0, -5px);
}
.pending-place:after {
  content: '';
  width: 8px;
  height: 8px;
  background: #1b81d2;
  border-radius: 8px;
  display: flex;
  transform: translate(18px, 22px);
}
</style>
